import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { userAPI } from '@/api/userAPI'
import Login from '@/components/auth/Login.vue'
import Register from '@/components/auth/Register.vue'
import Layout from '@/views/Layout.vue'
import SmartHome from '@/components/farm/SmartHome.vue'
import SmartPlanting from '@/components/farm/SmartPlanting.vue'
import SmartPigsty from '@/components/farm/SmartPigsty.vue'
import SmartPond from '@/components/farm/SmartPond.vue'
import UserProfile from '@/views/user/UserProfile.vue'

// 导入后台管理相关组件
import AdminLayout from '@/views/AdminLayout.vue'
import UserManagement from '@/views/admin/UserManagement.vue'
// 导入设备管理组件（需自行创建对应文件）
import DeviceManagement from '@/views/admin/DeviceManagement.vue'

const routes = [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login, meta: { isPublic: true } },
    { path: '/register', component: Register, meta: { isPublic: true } },
    {
        path: '/dashboard',
        component: Layout,
        meta: { requiresAuth: true },
        children: [
            { path: '', redirect: 'smart-home' },
            {
                path: 'smart-home',
                component: SmartHome,
                meta: { title: '智慧家居' },
                children: [
                    {
                        path: 'home-air', // 规范路径（小写横杠）
                        alias: ['HomeAir'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartHome/HomeAir.vue'),
                        meta: { title: '智能换气' }
                    },
                    {
                        path: 'home-potted',
                        alias: ['HomePotted'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartHome/HomePotted.vue'),
                        meta: { title: '智能盆栽' }
                    },
                    {
                        path: 'home-alert',
                        alias: ['HomeAlert'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartHome/HomeAlert.vue'),
                        meta: { title: '智能安防' }
                    }
                ]
            },
            {
                path: 'smart-planting',
                component: SmartPlanting,
                meta: { title: '智慧种植' },
                children: [
                    {
                        path: 'planting-water',
                        alias: ['PlantingWater'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPlanting/PlantingWater.vue'),
                        meta: { title: '智能灌溉' }
                    },
                    {
                        path: 'planting-air',
                        alias: ['PlantingAir'], // 修复拼写错误：PlantingAit → PlantingAir
                        component: () => import('@/components/farm/SmartPlanting/PlantingAir.vue'),
                        meta: { title: '智能通风' }
                    }
                ]
            },
            {
                path: 'smart-pigsty',
                component: SmartPigsty,
                meta: { title: '智慧猪舍' },
                children: [
                    {
                        path: 'pigsty-water',
                        alias: ['PigstyWater'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPigsty/PigstyWater.vue'),
                        meta: { title: '智能供水' }
                    },
                    {
                        path: 'pigsty-air',
                        alias: ['PigstyAir'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPigsty/PigstyAir.vue'),
                        meta: { title: '智能风扇' }
                    },
                    {
                        path: 'pigsty-alert',
                        alias: ['PigstyAlert'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPigsty/PigstyAlert.vue'),
                        meta: { title: '智能防控' }
                    }
                ]
            },
            {
                path: 'smart-pond',
                component: SmartPond,
                meta: { title: '智慧鱼塘' },
                children: [
                    {
                        path: 'pond-air',
                        alias: ['PondAir'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPond/PondAir.vue'),
                        meta: { title: '鱼塘风扇' }
                    },
                    {
                        path: 'pond-water',
                        alias: ['PondWater'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPond/PondWater.vue'),
                        meta: { title: '鱼塘水泵' }
                    },
                    {
                        path: 'pond-alert',
                        alias: ['PondAlert'], // 兼容大写开头路径
                        component: () => import('@/components/farm/SmartPond/PondAlert.vue'),
                        meta: { title: '鱼塘警报' }
                    }
                ]
            },
            { path: 'user-profile', component: UserProfile, meta: { title: '个人中心' } }
        ]
    },
    {
        path: '/admin',
        component: AdminLayout,
        meta: {
            requiresAuth: true,
            requiresAdmin: true,
            title: '后台管理系统'
        },
        children: [
            {
                path: 'users',
                name: 'AdminUsers',
                component: UserManagement,
                meta: {
                    title: '用户权限管理',
                    description: '管理不同角色：管理员、农户、养殖户',
                    icon: '👥',
                    requiresAuth: true,
                    requiresAdmin: true
                }
            },
            // 新增：设备管理路由（与用户管理同层级）
            {
                path: 'devices',
                name: 'AdminDevices',
                component: DeviceManagement,
                meta: {
                    title: '设备管理',
                    description: '管理物联网设备：状态、配置、数据监控',
                    icon: '🔧',
                    requiresAuth: true,
                    requiresAdmin: true
                }
            },
            {
                path: '',
                redirect: { name: 'AdminUsers' }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 全局防抖函数：避免重复弹窗
let debounceTimer = null
function debounce(fn, delay = 3000) {
    return function(...args) {
        if (debounceTimer) clearTimeout(debounceTimer)
        debounceTimer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

// 过期提示防抖处理
const showExpireAlert = debounce((message) => {
    alert(message)
})

// 增强的路由守卫 - 基于 authStore 统一校验
router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()
    const user = authStore.user
    const isLoginValid = authStore.isLoggedIn()
    const isAdmin = authStore.isAdmin()

    console.log('🔄 路由守卫检查:', {
        from: from.path,
        to: to.path,
        isPublic: to.meta.isPublic || false,
        requiresAuth: to.meta.requiresAuth || false,
        requiresAdmin: to.meta.requiresAdmin || false,
        isLoginValid: isLoginValid,
        isAdmin: isAdmin,
        user: user ? {
            phone: user.phone,
            role: user.role,
            status: user.status,
            rawLoginTime: user.rawLoginTime,
            loginTime: user.loginTime ? new Date(user.loginTime) : null
        } : null
    })

    if (to.meta.isPublic) {
        if (isLoginValid) {
            console.log('✅ 已登录，重定向到智慧家居')
            next('/dashboard/smart-home')
            return
        }
        console.log('✅ 公开页面，允许访问')
        next()
        return
    }

    if (!isLoginValid) {
        console.log('❌ 前端校验：未登录或登录已过期，重定向到登录页')
        showExpireAlert('登录状态已过期，请重新登录')
        next('/login')
        return
    }

    try {
        console.log('🔍 开始后端认证校验...')
        const authStatus = await userAPI.checkAuthStatus()
        if (!authStatus.isAuthenticated) {
            console.log('❌ 后端校验：认证失败，清理本地数据并跳转登录')
            authStore.logout()
            showExpireAlert('登录状态已失效，请重新登录')
            next('/login')
            return
        }
        console.log('✅ 后端校验：认证通过')
    } catch (error) {
        // 仅401/403判定为认证失败，其他错误提示服务异常
        const isAuthError = error.response?.status === 401 || error.response?.status === 403
        if (isAuthError) {
            console.error('❌ 后端认证校验出错（权限/登录失效）：', error)
            showExpireAlert('登录状态已失效，请重新登录')
            authStore.logout()
            next('/login')
        } else {
            console.error('❌ 后端认证接口调用失败（非认证错误）：', error)
            showExpireAlert('服务异常，请稍后重试')
            next(false) // 阻止跳转，保留当前状态
        }
        return
    }

    if (to.meta.requiresAdmin && !isAdmin) {
        console.log('🚫 权限不足：非管理员用户，禁止访问后台管理')
        showExpireAlert('您没有管理员权限，无法访问该页面')
        next('/dashboard/smart-home')
        return
    }

    if (user && user.status !== 1) {
        console.log('🚫 用户状态异常（状态码：', user.status, '），禁止访问')
        showExpireAlert('您的账号状态异常，无法继续操作，请联系管理员')
        authStore.logout()
        next('/login')
        return
    }

    console.log('✅ 所有校验通过，允许访问:', to.path)
    next()
})

router.afterEach((to, from) => {
    console.log('📍 导航完成:', {
        from: from.path,
        to: to.path,
        success: true
    })

    const pageTitle = to.meta.title || '智慧农场管理系统'
    document.title = `${pageTitle} - 智慧农场管理系统`

    const authStore = useAuthStore()
    if (authStore.isLoggedIn()) {
        console.log('📝 用户活动记录 - 页面导航:', to.path)
    }
})

router.onError((error) => {
    console.error('💥 路由错误:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    showExpireAlert('页面加载失败，请刷新重试或重新登录')
})

router.isReady().then(() => {
    console.log('✅ 路由初始化完成')

    const authStore = useAuthStore()
    const isFrontValid = authStore.isLoggedIn()

    console.log('🚀 应用启动认证检查:', {
        hasUserInfo: !!authStore.user,
        isFrontValid: isFrontValid,
        user: authStore.user ? {
            phone: authStore.user.phone,
            role: authStore.user.role,
            rawLoginTime: authStore.user.rawLoginTime,
            loginTime: authStore.user.loginTime ? new Date(authStore.user.loginTime) : null
        } : null
    })

    if (authStore.user && !isFrontValid) {
        console.warn('⚠️ 前端检测到无效用户信息，自动清理')
        authStore.logout()
        if (!window.location.pathname.includes('/login')) {
            router.push('/login')
        }
        return
    }

    if (isFrontValid) {
        console.log('🔍 应用启动：前端校验通过，进行后端认证检查')
        userAPI.checkAuthStatus().then(status => {
            if (!status.isAuthenticated) {
                console.warn('⚠️ 后端检测到无效用户信息，自动清理')
                authStore.logout()
                if (!window.location.pathname.includes('/login')) {
                    router.push('/login')
                }
            } else {
                console.log('✅ 应用启动：前后端认证均通过')
            }
        }).catch(error => {
            console.error('❌ 应用启动：后端认证检查失败（非认证错误）', error)
            // 非401/403错误不强制登出，仅提示
            showExpireAlert('服务异常，部分功能可能受限，请稍后重试')
        })
    }

}).catch((error) => {
    console.error('❌ 路由初始化失败:', error)
})

function checkLoginExpiry() {
    const authStore = useAuthStore()
    const user = authStore.user

    if (!user) return false

    const isFrontValid = authStore.isLoggedIn()
    if (!isFrontValid) {
        console.log('🔐 前端检测：登录状态已过期，自动登出')
        authStore.logout()
        return true
    }

    if (window.loginCheckCounter % 3 === 0) {
        console.log('🔍 执行后端登录状态校验...')
        userAPI.checkAuthStatus().then(status => {
            if (!status.isAuthenticated) {
                console.log('🔐 后端检测：登录状态已过期，自动登出')
                authStore.logout()
                if (!window.location.pathname.includes('/login')) {
                    router.push('/login')
                    showExpireAlert('登录状态已过期，请重新登录')
                }
            }
        }).catch(error => {
            console.error('❌ 后端登录状态校验失败（非认证错误）', error)
        })
    }

    const currentTime = new Date().getTime()
    const loginTime = user.loginTime
    const EXPIRE_HOURS = 24
    const expiresIn = EXPIRE_HOURS * 60 * 60 * 1000
    const remainingTime = expiresIn - (currentTime - loginTime)

    if (remainingTime < 5 * 60 * 1000 && remainingTime > 0) {
        const remainingMinutes = Math.round(remainingTime / 1000 / 60)
        console.warn('⚠️ 登录状态即将过期，剩余时间:', remainingMinutes + '分钟')
        showExpireAlert(`登录状态即将过期，剩余${remainingMinutes}分钟，请及时保存工作并重新登录`)
    }

    const remainingHours = Math.floor(remainingTime / (60 * 60 * 1000))
    const remainingMins = Math.floor((remainingTime % (60 * 60 * 1000)) / (60 * 1000))
    console.log('🔐 登录状态有效，剩余时间:', `${remainingHours}小时${remainingMins}分钟`)

    window.loginCheckCounter = (window.loginCheckCounter || 0) + 1
    return false
}

let loginCheckInterval = null

function startLoginCheck() {
    if (loginCheckInterval) {
        clearInterval(loginCheckInterval)
    }

    loginCheckInterval = setInterval(() => {
        const authStore = useAuthStore()
        if (authStore.user) {
            const isExpired = checkLoginExpiry()
            if (isExpired && !window.location.pathname.includes('/login')) {
                console.log('🔐 登录已过期，重定向到登录页')
                showExpireAlert('登录状态已过期，请重新登录')
                router.push('/login')
            }
        }
    }, 30000)

    console.log('✅ 启动登录状态检查（每30秒一次）')
}

function stopLoginCheck() {
    if (loginCheckInterval) {
        clearInterval(loginCheckInterval)
        loginCheckInterval = null
        console.log('🛑 停止登录状态检查')
    }
}

startLoginCheck()

window.addEventListener('beforeunload', () => {
    stopLoginCheck()
})

document.addEventListener('visibilitychange', () => {
    const authStore = useAuthStore()
    if (document.hidden) {
        if (!authStore.user) {
            console.log('📱 页面不可见且无用户信息，暂停登录检查')
            stopLoginCheck()
        }
    } else {
        console.log('📱 页面可见，恢复登录检查')
        startLoginCheck()
        if (authStore.user) {
            checkLoginExpiry()
        }
    }
})

export default router